package com.xin.utils;

import com.xin.exception.MyException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage;
import java.util.Date;


/**
 * 发送邮件服务
 */
public class EmailUtils {


    public static  void sendEmail(String subject,JavaMailSender javaMailSender,String to,String token){
        String url = "http://127.0.0.1:9999/shop/activeAccount?token="+token;
        String html="<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>Title</title>\n" +
                "</head>\n" +
                "<body>\n" +
                "  <div>\n" +
                "      <h2>恭喜您，账号开通成功</h2>\n" +
                "      <a href='"+url+"'>请您在3天之内激活</a>\n"+
                "  </div>\n" +
                "</body>\n" +
                "</html>";
        //发送邮件
        send(javaMailSender,html,to,subject);
    }


    /**
     *通过模板发送邮件
     * @param subject 邮件主题
     * @param javaMailSender
     * @param to 发送给谁
     * @param html 邮件模板
     */
    public static  void sendEmailByTemplate(String subject,JavaMailSender javaMailSender,String to,String html){
        send(javaMailSender,html,to,subject);
    }


    /**
     * 发送邮件
     * @param javaMailSender
     * @param html
     * @param to
     * @param subject
     */
    public static void send(JavaMailSender javaMailSender,String html,String to,String subject){
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,"utf-8"); try {
            //设置发送人
            helper.setTo(to);
            helper.setFrom("1165802056@qq.com");
            helper.setSubject(subject);
            //邮件内容
            helper.setText(html,true);
            helper.setSentDate(new Date());
            javaMailSender.send(mimeMessage);
        }catch (Exception e){
            e.printStackTrace();
            throw new MyException("发送邮件繁忙，请重新输入");
        }
    }
}
